package com.qdxwx.web.controller.course;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.course.CourseFileService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.data.service.user.UserCountService;
import com.qdxwx.data.service.user.UserDownloadService;
import com.qdxwx.models.course.CourseFile;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/course")
public class CourseDownloadController extends BaseController {
    @Autowired
    private UserBuyService userBuyService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private CourseFileService courseFileService;
    @Autowired
    private UserDownloadService userDownloadService;
    /**
     * 下载
     */
    @RequestMapping(value = {"/download.json"})
    @ResponseBody
    public AjaxResult Download(HttpServletRequest request) throws IOException {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.error("此功能需要登录才能下载");
        }
        int fileId = TKConvert.toInteger(request.getParameter("id"));
        CourseFile courseFile = courseFileService.get(fileId);
        if (courseFile == null) {
            return AjaxResult.error("找不到指定文件");
        }
        boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.COURSE.ordinal(),courseFile.getCourseId());
        if (!isBuy) {
            return AjaxResult.error("您未报名该课程，请报名后操作！");
        }
        //courseFileService.updateDown(fileId);
        userCountService.updateCourseDownCount(user.getUserId(),1);
        userDownloadService.create(courseFile, user);
        return AjaxResult.success(courseFile.getFileUrl(), 1);
    }
}
